package at.favre.lib.armadillo;

import ohos.data.preferences.Preferences;
import org.jetbrains.annotations.NotNull;

/**
 * Implementation that will wrap a {@link OnSecurePreferenceChangeListener} to adapt to the standard {@link Preferences.PreferencesObserver}
 *
 * @since 0.9.0
 */
final class SharedPreferenceChangeListenerWrapper implements Preferences.PreferencesObserver {

    private static final class KeyComparisonImpl implements OnSecurePreferenceChangeListener.DerivedKeyComparison {
        private final EncryptionProtocol encryptionProtocol;
        private final String derivedContentKey;

        private KeyComparisonImpl(EncryptionProtocol encryptionProtocol, String derivedContentKey) {
            this.encryptionProtocol = encryptionProtocol;
            this.derivedContentKey = derivedContentKey;
        }

        @Override
        public boolean isDerivedKeyEqualTo(@NotNull String key) {
            return derivedContentKey.equals(encryptionProtocol.deriveContentKey(key));
        }
    }

    private final OnSecurePreferenceChangeListener wrappedListener;
    @NotNull
    private final EncryptionProtocol encryptionProtocol;
    @NotNull
    private final Preferences securedPrefs;

    SharedPreferenceChangeListenerWrapper(@NotNull OnSecurePreferenceChangeListener wrapped, @NotNull EncryptionProtocol encryptionProtocol, @NotNull Preferences securedPrefs) {
        wrappedListener = wrapped;
        this.encryptionProtocol = encryptionProtocol;
        this.securedPrefs = securedPrefs;
    }

    OnSecurePreferenceChangeListener getWrapped() {
        return wrappedListener;
    }

    @Override
    public void onChange(Preferences preferences, String key) {
        if (key != null) {
            wrappedListener.onSecurePreferenceChanged(securedPrefs, new KeyComparisonImpl(encryptionProtocol, key));
        }
    }
}
